import { AuthContext } from "../App";
import { useContext, useState } from "react";

const initialState = {
    email:"",
    password:'',
    isSubmitting:false,
    errorMessage:null
}

export default function Login(props) {

    const {authDispatch} = useContext(AuthContext);  
    
    const [data,setData] = useState(initialState);

    const change  = (e) => {
        
        setData({
            ...data,
            [e.target.name]:e.target.value
        })
    }

    const handleFormSubmit = (e) => {
        e.preventDefault();
        setData({
            ...data,
            isSubmitting:true,
            errorMessage:null
        })
        fetch("https://www.fastmock.site/mock/4f8c468ae7202f91850147535d932340/sbt/ali/login",{
            method:"POST",
            headers:{
                "Content-type":"application/json"
            },
            body:JSON.stringify({
                username:data.email,
                password:data.password
            })
        })
            .then(res => res.json())
            .then(data => {
                console.log("请求的data:",data);
                authDispatch({type:'LOGIN',payload:{
                    user:data.user,
                    token:data.token
                }});
                
            })

    }

    return (
        <div className="login-container">
            <div className="card" >
                <div className="container" >
                    <form onSubmit={handleFormSubmit}>
                        <h1>Login</h1>
                        <label htmlFor="email" />Email address:
                        <input type="email"
                            value={data.email}
                            id="email"
                            name="email"
                            onChange={change}
                            
                            />
                        
                        <label htmlFor="password" />Password:
                        <input type="password"
                            value={data.password}
                            id="password"
                            name="password"
                            onChange={change}
                            
                            />
                        
                        <input type="submit" disabled={data.isSubmitting} value="登陆" />
                        <input type="submit" value="注册" />
                        
                    </form>
                </div>
                
            </div>
        
        </div>
    )
}